package com.tk.exam.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.util.StringUtils;
import com.tk.exam.config.properties.DataBaseProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;


@Slf4j
@Configuration
public class DruidConfig {

    @Autowired
    private DataBaseProperties dataBaseProperties;

    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dataBaseProperties.getDbUrl());
        datasource.setUsername(dataBaseProperties.getDbUsername());
        datasource.setPassword(dataBaseProperties.getDbPassword());
        datasource.setDriverClassName(dataBaseProperties.getDriverClassName());
        datasource.setInitialSize(StringUtils.stringToInteger(dataBaseProperties.getDruidPoolInitialSize()));
        datasource.setMinIdle(StringUtils.stringToInteger(dataBaseProperties.getDruidPoolMinIdle()));
        datasource.setMaxActive(StringUtils.stringToInteger(dataBaseProperties.getDruidPoolMaxActive()));
        datasource.setMaxWait(Long.parseLong(dataBaseProperties.getDruidPoolMaxWait()));
        datasource.setTimeBetweenEvictionRunsMillis(Long.parseLong(dataBaseProperties.getDruidPoolTimeBetweenEvictionRunsMillis()));
        datasource.setMinEvictableIdleTimeMillis(Long.parseLong(dataBaseProperties.getDruidPoolMinEvictableIdleTimeMillis()));
        datasource.setValidationQuery(dataBaseProperties.getDruidPoolValidationQuery());
        datasource.setTestWhileIdle(Boolean.parseBoolean(dataBaseProperties.getDruidPoolTestWhileIdle()));
        datasource.setTestOnBorrow(Boolean.parseBoolean(dataBaseProperties.getDruidPoolTestOnBorrow()));
        datasource.setTestOnReturn(Boolean.parseBoolean(dataBaseProperties.getDruidPoolTestOnReturn()));
        datasource.addFilters("config");
        datasource.setConnectionProperties(dataBaseProperties.getDruidPoolConnectionProperties());
        return datasource;
    }
}
